package com.hjq.mallauth.controller;

import com.alibaba.fastjson.JSON;
import com.hjq.common.constants.AuthConstants;
import com.hjq.common.entity.vo.UserAccountVO;
import com.hjq.common.utils.R;
import com.hjq.mallauth.entity.vo.UserLoginVO;
import com.hjq.mallauth.entity.vo.UserRegVO;
import com.hjq.mallauth.feign.MemberFeign;
import com.hjq.mallauth.feign.ThirdPartyFeign;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;

/**
 * @auther HJQ
 */
@Controller
public class AuthController {
    @Autowired
    ThirdPartyFeign thirdPartyFeign;
    @Autowired
    StringRedisTemplate redisTemplate;
    @Autowired
    MemberFeign memberFeign;


    @GetMapping("/logout.html")
    public String  doLogOut(HttpSession session){
        session.invalidate();
        return  "redirect:http://auth.hjqmall.com/login.html";
        }
    @PostMapping("/login")
    public String  doLogin(UserLoginVO userLoginVO,RedirectAttributes attributes,HttpSession session){

        R login = memberFeign.login(userLoginVO);
        if(login.getCode()!=0){
            Map<String,String> errors=new HashMap<>();
            errors.put("msg",  (String) login.get("msg"));
            attributes.addFlashAttribute("errors",errors);
            return  "redirect:http://auth.hjqmall.com/login.html";

        }


        String string = JSON.toJSONString(login.get("account"));
        UserAccountVO accountVO = JSON.parseObject(string, UserAccountVO.class);
        //TODO 1.解决子域的session共享问题 2，希望json序列化方式到redis中
        session.setAttribute(AuthConstants.LOGIN_USER,accountVO);
        return  "redirect:http://hjqmall.com";
    }

    @GetMapping("/sms/send")
    @ResponseBody
    public R  sendCode(@RequestParam("phoneNum") String phoneNum){
        String codeValue = redisTemplate.opsForValue().get(AuthConstants.SMS_CODE + phoneNum);
        if(!StringUtils.isEmpty(codeValue)){
            long l = Long.parseLong(codeValue.split("_")[1]);
            if(System.currentTimeMillis()-l<60000L){
                return  R.error(100,"验证码验证时间太短");
            }

        }
        String code=phoneNum.substring(0,5)+"_"+System.currentTimeMillis();
        redisTemplate.opsForValue().set(AuthConstants.SMS_CODE + phoneNum,code);
        thirdPartyFeign.sendCode(phoneNum);
        return R.ok();
    }
    @RequestMapping("/register")
    public  String redisterFinish(@Valid UserRegVO regVO, BindingResult result, RedirectAttributes attributes){
        if (result.hasErrors()){
            Map<String,String> errors=new HashMap<>();
            result.getFieldErrors().forEach(error->{
                String defaultMessage = error.getDefaultMessage();
                errors.put(error.getField(),defaultMessage);
            });
            attributes.addFlashAttribute("errors",errors);

            return "redirect:http://auth.hjqmall.com/reg.html";
        }
        //注册
         String code = regVO.getCode();
        String codeFromCache = redisTemplate.opsForValue().get(AuthConstants.SMS_CODE + regVO.getPhoneNum());
        if(StringUtils.isEmpty(codeFromCache)){
           Map<String,String> errors=new HashMap<>();
           errors.put("code","验证码过期或错误");
            attributes.addFlashAttribute("errors",errors);
            return "redirect:http://auth.hjqmall.com/reg.html";
        }
        if (!code.equals(codeFromCache.split("_")[0])){
            Map<String,String> errors=new HashMap<>();
            errors.put("code","验证码过期或错误");
            attributes.addFlashAttribute("errors",errors);
            return "redirect:http://auth.hjqmall.com/reg.html";
        }
        //完成注册
        R register = memberFeign.register(regVO);
        if(register.getCode()!=0){
            //注册失败
            Map<String,String> errors=new HashMap<>();
            errors.put("msg",(String) register.get("msg"));
            attributes.addFlashAttribute("errors",errors);

            return  "redirect:http://auth.hjqmall.com/reg.html";

        }

        //删除验证码
        redisTemplate.delete(AuthConstants.SMS_CODE + regVO.getPhoneNum());

        return  "redirect:http://auth.hjqmall.com/login.html";

    }
    @RequestMapping("/login.html")
    public  String Login(HttpSession httpSession){
        if(httpSession.getAttribute(AuthConstants.LOGIN_USER)==null){
            return  "login";
        }
        else {
            return  "redirect:http://hjqmall.com";
        }
    }

}
